package com.usian.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.usian.admin.feign.ArticleFeign;
import com.usian.admin.feign.MediaFeign;
import com.usian.admin.mapper.AdChannelMapper;
import com.usian.admin.mapper.AdSensitiveMapper;
import com.usian.admin.service.WemediaNewsAutoScanService;
import com.usian.common.aliyun.GreeTextScan;
import com.usian.common.aliyun.GreenImageScan;
import com.usian.common.constants.WemediaContans;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.wemedia.vo.WmNewsVo;
import com.usian.utils.common.SensitiveWordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class WemediaNewsAutoScanServiceImpl extends BaseServiceImpl<AdChannelMapper, AdChannel> implements WemediaNewsAutoScanService {

    @Value("${fastDfs}")
    private String baseUrl;

    @Autowired
    private MediaFeign mediaFeign;

    @Autowired
    private FastDFSClient client;

    @Autowired
    private GreeTextScan textScan;

    @Autowired
    private GreenImageScan imageScan;

    @Autowired
    private AdSensitiveMapper adSensitiveMapper;

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private AdChannelMapper adChannelMapper;

    //@GlobalTransactional
    @Override
    public ResponseResult autoScanByMediaNewsId(Integer id) {
        if (id == null) return paramError;
        WmNews news = mediaFeign.findById(id);
        if (news == null) return noData;
        //刚发布还未审核
        if (news.getStatus() == WmNews.Status.SUBMIT.getCode()) {
            //拼接字符串和要的图片 同步阻塞
            StringBuilder checkString = new StringBuilder();
            List<byte[]> imageList = new ArrayList<>();
            //获取发布新闻的内容
            String content = news.getContent();
            JSONArray array = JSON.parseArray(content);
            array.forEach(a -> {
                //转成字符串
                JSONObject object = JSON.parseObject(a.toString());
                if (object.get("type").equals(WemediaContans.WM_NEWS_TYPE_IMAGE)) {
                    String url = (String) object.get("value");
                    String replace = url.replace("http://192.168.58.138/", "");
                    //拿到第一个斜杠的位置
                    int i = replace.indexOf("/");
                    try {
                        byte[] download = client.download(replace.substring(0, i), replace.substring(i + 1, (replace + 0).length() - 1));
                        imageList.add(download);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    String text = (String) object.get("value");
                    checkString.append(text);
                }
            });
            //审文本
            try {
                Map map = textScan.greeTextScan(checkString.toString());
                if (map.get("suggestion").equals("block")) {
                    //修改状态为2
                    updateNewsStatus(news, 2);
                    return ResponseResult.okResult("审核未通过");
                } else if (map.get("suggestion").equals("review")) {
                    //修改状态为3
                    updateNewsStatus(news, 3);
                    return ResponseResult.okResult("审核不确定，人工走一圈吧");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                Map map = imageScan.imageScan(imageList);
                if (map.get("suggestion").equals("block")) {
                    //修改状态为2
                    updateNewsStatus(news, 2);
                    return ResponseResult.okResult("审核未通过");
                } else if (map.get("suggestion").equals("review")) {
                    //修改状态为3
                    updateNewsStatus(news, 3);
                    return ResponseResult.okResult("审核不确定，人工走一圈吧");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //敏感词匹配，查询所有的敏感词
            List<String> allSensitive = adSensitiveMapper.findAllSensitive();
            //初始化敏感词
            SensitiveWordUtil.initMap(allSensitive);
            //初始化文章内容
            Map<String, Integer> words = SensitiveWordUtil.matchWords(checkString.toString());
            //有敏感词表示失败
            if (words.size() != 0) {
                updateNewsStatus(news, 2);
                return ResponseResult.okResult("审核未通过");
            }
            //对比时间
            if (news.getPublishTime() != null) {
                //指定发布时间
                long time = news.getPublishTime().getTime();
                //当前时间
                long l = System.currentTimeMillis();
                if (time > l) {
                    updateNewsStatus(news, 8);
                    return ResponseResult.okResult("审核通过待发布");
                }
            }
            publish(news);
        }
        if (news.getStatus() == WmNews.Status.SUCCESS.getCode() || news.getStatus() == WmNews.Status.ADMIN_SUCCESS.getCode()) {
            long time = news.getPublishTime().getTime();
            long l = System.currentTimeMillis();
            if (l > time) publish(news);
        }
        return null;
    }

    private ResponseResult publish(WmNews news) {
        WmUser wmUser = mediaFeign.findById1(news.getUserId());
        if (wmUser == null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        AdChannel adChannel = adChannelMapper.selectById(news.getChannelId());
        ApArticle apArticle = saveArticle(news, wmUser, adChannel);
        news.setArticleId(apArticle.getId());
        updateNewsStatus(news, 9);
        return ResponseResult.okResult("已发布");
    }

    private ApArticle saveArticle(WmNews news, WmUser wmUser, AdChannel adChannel) {
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(news.getTitle());
        apArticle.setAuthorId(wmUser.getApAuthorId().longValue());
        apArticle.setAuthorName(wmUser.getName());
        apArticle.setChannelId(news.getChannelId());
        apArticle.setChannelName(adChannel.getName());
        apArticle.setLayout(news.getType() == 3 ? 2 : news.getType());
        apArticle.setFlag((byte) 0);
        apArticle.setImages(news.getImages());
        apArticle.setLikes(0);
        apArticle.setViews(0);
        apArticle.setComment(0);
        apArticle.setCollection(0);
        apArticle.setCreatedTime(news.getCreatedTime());
        apArticle.setPublishTime(new Date());
        articleFeign.saveArticle(apArticle);

        ApArticleContent articleContent = new ApArticleContent();
        articleContent.setArticleId(apArticle.getId());
        articleContent.setContent(news.getContent());
        articleFeign.saveArticleContent(articleContent);
        ApArticleConfig config = new ApArticleConfig();
        config.setArticleId(apArticle.getId());
        config.setIsComment(false);
        config.setIsDelete(false);
        config.setIsForward(false);
        config.setIsDown(false);
        articleFeign.saveArticleConfig(config);
        return apArticle;
    }

    private void updateNewsStatus(WmNews news, int status) {
        news.setStatus((short) status);
        if (status == 2) news.setReason("审核失败，原因不明");
        if (status == 3) news.setReason("自动审核未明结果，请人工审核");
        if (status == 9) news.setReason("审核通过");
        if (status == 4) news.setReason("人工审核通过");
        mediaFeign.updateWmNews(news);
    }

    @Override
    public ResponseResult findNews(NewsAuthDto dto) {
        if (dto == null) return paramError;
        ResponseResult list = mediaFeign.findList(dto);
        list.setHost(baseUrl);
        return list;
    }

    @Override
    public ResponseResult findOne(Integer id) {
        if (id == null) return paramError;
        WmNewsVo wmNewsVo = mediaFeign.findWmNewsVo(id);
        ResponseResult<Object> result = new ResponseResult<>();
        result.setData(wmNewsVo);
        result.setHost(baseUrl);
        return result;
    }


    @Override
    public ResponseResult updateStatus(Integer type, NewsAuthDto dto) {
        if (dto == null) return paramError;
        if (type != 2 && type != 4) return paramError;
        int status = type == 0 ? 2 : 4;
        WmNews news = mediaFeign.findById(dto.getId());
        updateNewsStatus(news, status);
        return okResult;
    }
}
